import React, { useState, useEffect, useRef, useCallback } from 'react';
import './index.scss';
import { Icon, Content, Media } from 'react-fule-ui';
import { mediaData } from '../../mock/data';

export default function FuleScrollMore() {
  const scrollSpac = 100; // 滚动的距离参数
  const [scrollResult, setScrollResult] = useState(0); // 滚动停止最终位置
  const [showNext, setShowNext] = useState(true); // 控制显示next
  const domRef = useRef(null);
  // Hook 防抖
  function useDebounce(fn, delay, dep = []) {
    const { current } = useRef({ fn, timer: null });
    useEffect(() => {
      current.fn = fn;
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fn]);

    return useCallback((...args) => {
      if (current.timer) {
        clearTimeout(current.timer);
      }
      current.timer = setTimeout(() => {
        current.fn(...args);
      }, delay);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, dep);
  }
  // 左滑
  const funPrev1 = () => {
    let num = scrollResult - scrollSpac;
    if (num < 0) {
      num = 0;
    }
    setShowNext(true);
    setScrollResult(num);
  };
  // 右滑
  const funNext1 = () => {
    const itemDom = domRef.current || null; //dom
    const itemDomWidth = itemDom.getBoundingClientRect().width || null; //dom宽度
    const itemDomScrollWidth = itemDom.scrollWidth || null; // 滚动宽度
    let num = scrollResult + scrollSpac;
    if (num >= itemDomScrollWidth - itemDomWidth) {
      num = itemDomScrollWidth - itemDomWidth;
      setShowNext(false);
    }
    setScrollResult(num);
  };
  const funPrev = useDebounce(funPrev1, 30);
  const funNext = useDebounce(funNext1, 30);
  const scrollItem = (result) => {
    const itemDom = domRef.current || null; //dom
    const itemDomScrollLeft = itemDom.scrollLeft || null; // 元素滚动条到元素左边的距离
    const itemDomWidth = itemDom.getBoundingClientRect().width || null; //dom宽度
    const itemDomScrollWidth = itemDom.scrollWidth || null; // 滚动宽度
    if (itemDomScrollWidth - itemDomWidth < 0) {
      setShowNext(false);
    }
    const mistake = 2; // 2
    if (result > itemDomScrollLeft) {
      setTimeout(() => {
        if (itemDomScrollLeft > itemDomScrollWidth - itemDomWidth - mistake) {
          itemDom.scrollLeft = itemDomScrollLeft + mistake;
        } else {
          itemDom.scrollLeft = itemDomScrollLeft + mistake;
          scrollItem(result);
        }
        return;
      }, 1);
    }
    if (result < itemDomScrollLeft) {
      setTimeout(() => {
        itemDom.scrollLeft = itemDomScrollLeft - mistake;
        scrollItem(result);
      }, 1);
    }
  };
  useEffect(() => {
    scrollItem(scrollResult);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scrollResult]);

  // 一直监听原生滚动
  useEffect(() => {
    // const itemDom = document.querySelector('.FuleScrollMore-list'); //dom
    const itemDom = domRef.current || null; //dom
    const funScroll = () => {
      const itemDomWidth = itemDom.getBoundingClientRect().width || null; //dom宽度，
      const itemDomScrollWidth = itemDom.scrollWidth || null; // 滚动宽度
      const scrollLeftValue = itemDom.scrollLeft; // 元素滚动条到元素左边的距离
      setScrollResult(scrollLeftValue);
      if (
        scrollLeftValue > itemDomScrollWidth - itemDomWidth - 2 ||
        scrollLeftValue === itemDomScrollWidth - itemDomWidth
      ) {
        setShowNext(false);
      } else {
        setShowNext(true);
      }
    };
    itemDom.onscroll = () => {
      funScroll();
    };
    window.onresize = () => {
      funScroll();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [true]);

  return (
    <Content>
      <Content.Header>单选</Content.Header>
      <Content.Body>
        <div className="FuleScrollMore">
          <div className="FuleScrollMore-scroll" ref={domRef}>
            <div className="FuleScrollMore-main">
              {mediaData.map((item, index) => (
                <div
                  className="FuleScrollMore-item"
                  key={`FuleScrollMore-item-${index}`}
                >
                  <Media data={item} />
                </div>
              ))}
            </div>
            <div className="FuleScrollMore-action">
              {scrollResult !== 0 && (
                <div
                  className="FuleScrollMore-action__prev"
                  role="button"
                  onClick={funPrev}
                >
                  <Icon type="arrow" hover size="16" />
                </div>
              )}
              {!!showNext && (
                <div
                  className="FuleScrollMore-action__next"
                  role="button"
                  onClick={funNext}
                >
                  <Icon type="arrow" hover size="16" />
                </div>
              )}
            </div>
          </div>
        </div>
      </Content.Body>
    </Content>
  );
}
